package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天室服务端
 */
public class Server {//服务端
    private ServerSocket  serverSocket;
    private Map<String,PrintWriter> allOut = new HashMap<>();
    public Server(){//赋初始值
        try {
//创建服务端总机，同时申请并形成该服务端的端口号，后续一旦有客户端申请连接，会立即创建一个ServerSocket实例，返回一个Socket对象
            serverSocket = new ServerSocket(9999);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        //Socket accept() 该方法是个阻塞方法，调用该方法会卡住，直到一个客户端与其连接。
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                ClientHandler clientHandler = new ClientHandler(socket);
                Thread t1 = new Thread(clientHandler);
                t1.start();
            }
        } catch (IOException e) {
           e.printStackTrace();
        }
    }
    public static void main(String[] args) {
       Server server = new Server();
       server.start();
    }

    private  class ClientHandler implements Runnable{
        private Socket socket;
        private String host;
        private String nickName;
        public ClientHandler (Socket socket){
            this.socket = socket;
            host= socket.getInetAddress().getHostAddress();
        }
        @Override
        public void run() {
            PrintWriter pw = null;
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);
                nickName = br.readLine();
                synchronized (allOut) {
                    synchronized (allOut) {
                        allOut.put(nickName,pw);
                    }
                }
                sendMessageToAll("上线了，当前在线人数："+allOut.size());
                String line;
                while ((line = br.readLine()) != null) {
                   if (line.contains("@")){
                       sendMessageToOne(line);
                   }else {
                       sendMessageToAll("说："+line);
                   }
                }
            } catch (IOException e) {
            }finally {
                synchronized (allOut) {
                    synchronized (allOut) {
                        allOut.remove(nickName);
                    }
                }
                sendMessageToAll("下线了，当前人数："+allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }

        private void sendMessageToAll(String message){
            synchronized (allOut) {
                allOut.forEach((k,v)->v.println(k+"["+host+"]"+message));//迭代器循环遍历时，不允许通过集合的方式改变集合大小。
            }
        }

        private void sendMessageToOne(String message){
            if (message.matches("@.+：.+")){
                String tonickname = message.substring(1,message.indexOf(":"));
                if (allOut.containsKey(tonickname)){
                    String toMessage = message.substring(message.indexOf(":")+1);
                    allOut.get(tonickname).println(toMessage);
                }else {
                    allOut.get(nickName).println("用户"+tonickname+"不在线");
                }
            }else {
                allOut.get(nickName).println("格式不正确，请重新输入");
            }

            }

    }

}
